<?php
// .-----------------------------------------------------------------------------------
// | WE TRY THE BEST WAY 杭州博也网络科技有限公司
// |-----------------------------------------------------------------------------------
// | Author: 贝贝 <hebiduhebi@163.com>
// | Copyright (c) 2013-2016, http://www.itboye.com. All Rights Reserved.
// |-----------------------------------------------------------------------------------
namespace Admin\Controller;

use Admin\Api\LangApi;
use Admin\Util\ExcelHelper;
use Shop\Api\CategoryApi;
use Shop\Api\CategoryLangApi;
use Shop\Api\CategoryPropApi;

class CategoryController extends AdminController{


	public function index(){
		$lang_list = LangApi::getLangSupport();

		if(empty($lang_list)){
			$this->error('语言数据获取失败!');
		}
		$sel = getCateLang();

		$parent    = I('parent',0);
		$level     = I('level',0,'int');
		$map = array(
			'lang'=>$sel,
//			'parent'=>$parent
		);
		$map['level'] = ['lt',3];
		$name = I('name','');
		$params = array(
//			'parent'=>$parent
		);

		if(!empty($name)){
			$map['name'] = array('like',"%$name%");
			$params['name'] = $name;
		}

		$result = apiCall(CategoryApi::GET_INFO, array(array('id'=>$parent)));

		if(!$result['status']){
			$this->error($result['info']);
		}
		$parent_vo = $result['info'];
        $preparent = $parent_vo['parent'];

		$result = apiCall(CategoryApi::GET_INFO, array(array('id'=>$preparent)));
		$prepreparent = "";
		if($result['status']){
			$prepreparent = $result['info']['parent'];
            $preparent_vo = $result['info'];
		}

		$page = array('curpage' => I('get.p', 0), 'size' => 20);

		$order = "level asc, display_order desc ";
		//
		$result = apiCall(CategoryApi::QUERY,array($map,$page,$order,$params));

		//
		if($result['status']){
		    $list = $result['info']['list'];
            $list = $this->getChildren($list);
			$this->assign('level',$level);
            $this->assign('parent_vo',$parent_vo);
            $this->assign('preparent_vo',$preparent_vo);
			$this->assign('preparent',$preparent);
			$this->assign('parent',$parent);
			$this->assign('name',$name);
			$this->assign('lang_list',$lang_list);
			$this->assign('sel',$sel);
			$this->assign('show',$result['info']['show']);
			$this->assign('list',$list);
			$this->display();
		}else{
			LogRecord('INFO:'.$result['info'],'[FILE] '.__FILE__.' [LINE] '.__LINE__);
			$this->error(L('UNKNOWN_ERR'));
		}
	}


    public function level3(){
        $lang_list = LangApi::getLangSupport();

        if(empty($lang_list)){
            $this->error('语言数据获取失败!');
        }
        $sel = getCateLang();

        $parent    = I('parent',0);
        $level     = 3;
        $map = array(
            'lang'=>$sel,
            'level'=>$level,
//			'parent'=>$parent
        );
        $name = I('name','');
        $params = array(
//			'parent'=>$parent
        );

        if(!empty($name)){
            $map['name'] = array('like',"%$name%");
            $params['name'] = $name;
        }

        $page = array('curpage' => I('get.p', 0), 'size' => 20);

        $order = "display_order desc ";
        //
        $result = apiCall(CategoryApi::QUERY,array($map,$page,$order,$params));

        //
        if($result['status']){
            $list = $result['info']['list'];
            $list = $this->getParents($list);

            $this->assign('level',$level);
            $this->assign('parent',$parent);
            $this->assign('name',$name);
            $this->assign('lang_list',$lang_list);
            $this->assign('show',$result['info']['show']);
            $this->assign('list',$list);
            $this->display();
        }else{
            $this->error(L('UNKNOWN_ERR'));
        }
    }

    private function getChildren($list){
        $parent_ids = "";
        foreach ($list as $vo){
            if($vo['level'] > 1){
                $tmp = $vo['parent'].',';
                if(strpos($parent_ids,$tmp) === false){
                    $parent_ids .= $tmp;
                }
            }
        }
//        dump($parent_ids);
        $result = (new CategoryApi())->queryNoPaging(['id'=>['in',$parent_ids]]);
        $parent_list = $result['info'];
//        dump($parent_list);
        foreach ($list as &$vo) {
            foreach ($parent_list as $parent) {
                if($vo['parent'] == $parent['id']){
                    $vo['name'] = $parent['name'].'/'.$vo['name'];
                }
            }
        }
        return $list;
    }

    private function getParents($list){
        $parent_ids = "";
        foreach ($list as $vo){
            $parent_ids .= $vo['parent'].',';
        }
        $result = (new CategoryApi())->queryNoPaging(['id'=>['in',$parent_ids]]);
        $parent_list = $result['info'];
        $preparent_ids = "";
        foreach ($list as &$vo){
            foreach ($parent_list as $parent) {
                $tmp = $parent['parent'].',';

                if(strpos($preparent_ids,$tmp) === false){
                    $preparent_ids .= $tmp;
                }

                if($vo['parent'] == $parent['id']){
                    $vo['name'] = $parent['name'].'/'.$vo['name'];
                    $vo['preparent'] = $parent['parent'];
                    break;
                }
            }
        }
        $result = (new CategoryApi())->queryNoPaging(['id'=>['in',$preparent_ids]]);
        $preparent_list = $result['info'];
        foreach ($list as &$vo){
            foreach ($preparent_list as $parent) {
                if($vo['preparent'] == $parent['id']){
                    $vo['name'] = $parent['name'].'/'.$vo['name'];
                    break;
                }
            }
        }

        return $list;
    }

	/**
	 * 获取根节点下的一级节点
	 * @author hebidu <email:346551990@qq.com>
	 */
	private function getRootId($id){
		$result = apiCall(CategoryApi::GET_INFO,array(array('id'=>$id)));

		if($result['status'] && !empty($result['info']) && is_array($result['info'])){
			$cate_info = $result['info'];
			if($cate_info['parent'] == 0){
				return $cate_info['id'];
			}elseif($cate_info['parent'] > 0){
				$result = apiCall(CategoryApi::GET_INFO,array(array('id'=>$cate_info['parent'])));
				if($result['status'] && !empty($result['info']) && is_array($result['info'])){

					$cate_info = $result['info'];
					if($cate_info['parent'] == 0) {
						return $cate_info['id'];
					}
				}

			}
		}

		return 0;
	}


	/**
	 * 一级类目添加
	 */
	public function add(){
		if(IS_GET){

			$parent = I('get.parent',0);
			$icon = I('get.icon',0);
            $cate_list = $this->getCateList();
            $this->assign('cate_list',$cate_list);
			$this->assign("parent",$parent);
			$this->assign("lang",getCateLang());
			$this->assign("icon",$icon);
			$this->assign("lang_list",LangApi::getLangSupport());
			$this->display();
		}else{
            $cate = I('post.cate',0);
			$parent = $cate;//I('post.parent',0);
			$lang  = getCateLang();
			$root_id = $this->getRootId($parent);
			$langs = I('post.cate_lang',[]);
			$langs_value = [];
			$default_lang_value = "";
			foreach ($langs as $vo){
				$cate_lang_value = I('post.cate_lang_'.md5($vo),'');
                if($vo == 'zh-cn'){
                    $default_lang_value = $cate_lang_value;
                }
                if(empty($cate_lang_value)){
                    $cate_lang_value = $default_lang_value;
                }
				array_push($langs_value,$cate_lang_value);
			}
            $cateApi = new CategoryApi();
            $result  = $cateApi->getInfo(['id'=>$parent]);
            $level   = 0;
            $parent_vo = ['parent'=>0];
            if($result['status']){
                $parent_vo = $result['info'];
                $level = $parent_vo['level'];
            }

			if($level+1 > 3) $this->error('最多允许3级类目');
			$entity = array(
				'name'=>I('post.name'),
				'code'=>I('post.code'),
				'scope'=>I('post.scope'),
				'taxrate'=>I('post.taxrate'),
				'display_order'=>I('post.display_order'),
				'parent'=>$parent,
				'level'=>$level+1,
				'lang'=>$lang,
				'root_id'=>$root_id
			);

			$result = $cateApi->insertTrans($entity,$lang,$langs_value);

			if($result['status']){
				$this->success("添加成功！",U('Admin/Category/index',array('parent'=>$parent)));
			}else{
				$this->error($result['info']);
			}
		}
	}

	/**
	 * 编辑
	 */
	public function edit(){
        $id = I('get.id',0);
        if(empty($id)){
            $id = I('post.id',0);
        }

        $map = array('id'=>$id);
        $result = apiCall(CategoryApi::GET_INFO, array($map));

        if(!$result['status']) {
            $this->error($result['info']);
        }
        $cate = $result['info'];

		if(IS_GET){

			$parent = I('parent',-1);
			$preparent = I('preparent',0);

            $cateLangResult = (new CategoryLangApi())->queryNoPaging(['cate_id'=>$id]);
            if($cateLangResult['status']){
                $multLangs = $cateLangResult['info'];
                $langValueKeyArray = [];
                foreach ($multLangs as $vo){
                    $langValueKeyArray[$vo['lang']] = $vo['name'];
                }

                $this->assign("lang_value_key_array",$langValueKeyArray);
            }

            $this->assign("parent",$parent);
            $this->assign("preparent",$preparent);
            $this->assign("icon",$icon);
            $this->assign("cate",$result['info']);
            $this->assign("lang_list",LangApi::getLangSupport());
            $this->display();

		}else{
			$langs = I('post.cate_lang',[]);
			$langs_value = [];
            $default_lang_value = "";
            foreach ($langs as $vo){
                $cate_lang_value = I('post.cate_lang_'.md5($vo),'');
                if($vo == 'zh-cn'){
                    $default_lang_value = $cate_lang_value;
                }
                if(empty($cate_lang_value)){
                    $cate_lang_value = $default_lang_value;
                }
                array_push($langs_value,$cate_lang_value);
            }

			$entity = array(
				'name'=>I('post.name'),
				'code'=>I('post.code'),
				'scope'=>I('post.scope'),
				'taxrate'=>I('post.taxrate'),
				'display_order'=>I('post.display_order'),
				'icon'=>I('post.icon')
			);

			$model = M();
			$model->startTrans();
			$cateLangApi = new CategoryLangApi();
			$cateApi = new CategoryApi();
			$result = $cateApi->saveByID($id,$entity);
			if($result['status']){ 
				$result = $cateLangApi->updateCateLang($id,$langs,$langs_value);
			}
			
			if($result['status']){
				$model->commit();
				$this->success("编辑成功！",U('Admin/Category/index',array('parent'=>$parent)));
			}else{
				$model->rollback();
				$this->error($result['info']);
			}
		}
	}

	public function delete(){
		$id = I('get.id',0);
		$map = array('parent'=>$id);
		$result = apiCall(CategoryApi::QUERY,array($map));
		if($result['status']){
			if(count($result['info']['list']) > 0){
				$this->error("存在子类目，无法删除此类目！");
			}
            $result = (new CategoryLangApi())->delete(['cate_id'=>$id]);
			$result = apiCall(CategoryApi::DELETE,array(array('id'=>$id)));
			if($result['status']){
				$this->success("删除成功！");
			}else{
				$this->error($result['info']);
			}

		}else{

		}
	}

	/**
	 * 某一类目的所有属性
	 * @author hebidu <email:346551990@qq.com>
	 */
	public function cateAllProp(){

		if (IS_AJAX) {
			$cate_id = I('cate_id', 0);
			$map = array('cate_id' => $cate_id);

			$result = apiCall(CategoryApi::GET_INFO, array(array('id' => $cate_id)));

			if (!$result['status'] || empty($result['info'])) {
				$this->error('cate_id参数错误!');
			}

			$cate_info = $result['info'];

			$result = apiCall(CategoryPropApi::QUERY_PROP_TABLE, array($map));
			if (!$result['status']) {
				$this->error($result['info']);
			}

			$prop_table = $result['info'];
			//2. 父级类目获取
			$cate_id = intval($cate_info['parent']);
			$map = array('cate_id' => $cate_id);
			if ($cate_id > 0) {
				$result = apiCall(CategoryPropApi::QUERY_PROP_TABLE, array($map));
				if ($result['status'] && !empty($result['info'])) {
					$prop_table = array_merge($prop_table, $result['info']);
				}
				//3. 祖父级类目获取
				$result = apiCall(CategoryApi::GET_INFO, array(array('id' => $cate_id)));
				if ($result['status'] && is_array($result['info'])) {
					$cate_info = $result['info'];
					$cate_id = $cate_info['parent'];
					$map = array('cate_id' => $cate_id);
					if ($cate_id > 0) {
						$result = apiCall(CategoryPropApi::QUERY_PROP_TABLE, array($map));
						if ($result['status'] && !empty($result['info'])) {
							$prop_table = array_merge($prop_table, $result['info']);
						}
					}
				}
			}
            $lang_list = LangApi::getLangSupport();
            $lang[] = $lang_list;
			$prop_table = array_merge($prop_table,$lang);
			$this->success($prop_table);
		}
	}
    /**
     *
     */
	public function saveSort(){
        $ids = $this->_param('ids','');
        $sort = $this->_param('sort','');
        $id_arr = explode(",",$ids);
        $sort_arr = explode(",",$sort);
        $api = (new CategoryApi());

        for($i=0;$i<count($id_arr);$i++){
            if(empty($id_arr[$i])) continue;
            $result = $api->saveByID($id_arr[$i],['display_order'=>$sort_arr[$i]]);
        }

        $this->success('操作成功');
	}

	public function import(){

	    if(IS_GET){

            $cate_list = $this->getCateList();
            $cate_list = array_merge([['level'=>0,'name'=>'根类目','id'=>'0']],$cate_list);
            $this->assign("cate_list",$cate_list);
            $this->display();
	        return ;
        }

        $parent = $this->_param('cate',0);
	    $result = (new CategoryApi())->getInfo(['id'=>$parent]);
        $cateInfo = $result['info'];
        $root_id = 0;
        $level = 1;
	    if($result['status'] && is_array($cateInfo) ){
	        $root_id = $cateInfo['level'] == 1 ? $cateInfo['id']:$cateInfo['root_id'];
            $level = $cateInfo['level'] + 1;
        }

        if (! empty ( $_FILES ['import_file'] ['name'] )) {
            $tmp_file = $_FILES ['import_file'] ['tmp_name'];
            $file_types = explode(".", $_FILES ['import_file'] ['name']);
            $file_type = $file_types [count($file_types) - 1];
            /*判别是不是.xls文件，判别是不是excel文件*/
            if (strtolower($file_type) != "xlsx") {
                $this->error('不是Excel文件，重新上传');
            }
            /*设置上传路径*/
            $savePath = '.'.__ROOT__ . '/Public/Admin/upload/';
            /*以时间来命名上传的文件*/
            $str = date('Ymdhis').md5($_FILES ['import_file'] ['name'] );
            $file_name = $str . "." . $file_type;
            $fileFullPath = realpath($savePath).'/'. $file_name;

            /*是否上传成功*/
            if (!copy($tmp_file,($fileFullPath))) {
                $this->error('上传失败');
            }

            $data = (new ExcelHelper())->read($fileFullPath);
//            dump($data);
            $this->process($level,$root_id,$parent,$data);
        }
    }

    private function process($level,$root_id,$parent,$data){
	    //
        $startRow = 4;
        //语言开始列
        $langStartCol = 4;

        $totalRow = count($data);
        $totalEntity = [];
        for ( $i = $startRow + 1 ; $i < $totalRow ; $i ++){

            $entity = [
                'name'=>$data[$i][1],
                'level'=>$level,
                'en'=>$data[$i][2],
                'ko'=>$data[$i][3],
                'vi'=>$data[$i][4]
            ];

            array_push($totalEntity,$entity);
        }

        //将数据导入数据库

        $api = new CategoryApi();
        $langs = ['en','ko','vi'];
        foreach ($totalEntity as $item){
            $entity = [
                'name'=>$item['name'],
				'code'=>'',
				'scope'=>'',
				'taxrate'=>0,
				'display_order'=>I('post.display_order'),
				'parent'=>$parent,
				'level'=>$item['level'],
				'lang'=>'zh-cn',
				'root_id'=>$root_id
            ];

            $langs_value = [$item['en'],$item['ko'],$item['vi']];
//            dump($entity);
//            dump($langs_value);
            $api->insertTrans($entity,$langs,$langs_value);
        }
        $this->success("导入成功");
    }

    private function getCateList(){

        $result = (new CategoryApi())->queryNoPaging(null,"level asc,display_order desc");
        $cate_list = $result['info'];

        $list = [];
        $level1 = [];
        $level2 = [];
        $level3 = [];
        foreach ($cate_list as $item){
            if($item['level'] == 1){
                $list[$item['id']] = $item;
                $list[$item['id']]['_child'] = [];
            }
            if($item['level'] == 2){
                array_push($level2,$item);
            }
            if($item['level'] == 3){
                array_push($level3,$item);
            }
        }

        foreach ($level2 as $item2){
            $parent_id = $item2['parent'];
            $level2Child = &$list[$parent_id]['_child'];
            $level2Child[$item2['id']] = $item2;
            $level2Child[$item2['id']]['_child'] = [];
            foreach ($level3 as $item3) {
                $level3Child = &$level2Child[$item3['parent']]['_child'];
                array_push($level3Child,$item3);
            }
        }
        $list = array_values($list);
        $cate_list = [];
        foreach ($list as $vo){
            $name = $vo['name'];
            $level2 = $vo['_child'];
            unset($vo['_child']);
            array_push($cate_list,$vo);
            foreach ($level2 as $vo2){
                $vo2['name'] = $name.'/'.$vo2['name'];
                $level3 = $vo2['_child'];
                unset($vo2['_child']);
                array_push($cate_list,$vo2);
                foreach ($level3 as $vo3){
                    $vo3['name'] = $vo2['name'].'/'.$vo3['name'];
                    array_push($cate_list,$vo3);
                }
            }
        }

        return $cate_list;
    }


}

